<?php
/**
 * User: Administrator
 * Date: 13-6-28
 * Time: 下午7:48
 * 角色管理
 */

class RoleAction extends OauthAction{
    public function _initialize()
    {
        parent::_initialize();
        $this->_mode = D("Role");
    }

    //读取表单
    public function form(){
        $role_id = $this->_request('role_id');
        if($role_id){
            $this->assign('item', $this->_mode->find($role_id));
        }
        $this->display();
    }

    public function _before_save(){
        $data = $this->_post();
        if(empty($data['scrap'])){
            $data['role_name'] or ajax_return(L('role_name_lost'), 0);
            $condition = array();
            if(!empty($data['role_id'])){
                $condition['role_id'] = array('neq', $data['role_id']);
            }
            $condition['role_name'] = $data['role_name'];
            $total = $this->_mode->where($condition)->count();
            if($total > 0) ajax_return(L('role_name_exists'), 0);
        }
    }

    public function _before_drop(){
        $itemid = $this->_request('itemid');
        if(strpos($itemid, ',')){
            $itemid = explode(',', $itemid);
        }else{
            $itemid = array($itemid);
        }
        foreach($itemid as $item){
            if(D('Master')->where("find_in_set(role_ids, '%d')", $item)->count() > 0) ajax_return(L('drop_master_before'), 0);
        }
    }

    /**
     * 分配权限
     * @param $role_id
     */
    public function competence($role_id){
        $this->assign('menu_id', base64_encode($this->_mode->where("role_id = '%d'", $role_id)->getField('menu_id')));
        $this->assign('role_id', $role_id);
        $this->display();
    }
}